package com.yoomiito.app;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.provider.Settings;

import androidx.annotation.NonNull;

import com.google.android.material.bottomnavigation.BottomNavigationItemView;
import com.google.android.material.bottomnavigation.BottomNavigationMenuView;
import com.google.android.material.bottomnavigation.BottomNavigationView;

import androidx.fragment.app.Fragment;
import androidx.core.app.NotificationManagerCompat;
import androidx.core.content.FileProvider;

import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.blankj.rxbus.RxBus;
import com.yoomiito.app.base.App;
import com.yoomiito.app.base.BaseActivity;
import com.yoomiito.app.model.LiveUserInfo;
import com.yoomiito.app.model.bean.UserInfo;
import com.yoomiito.app.model.bean.VersionInfo;
import com.yoomiito.app.present.MainPresenter;
import com.yoomiito.app.ui.fragment.GasStationListFragment;
import com.yoomiito.app.ui.fragment.GiftFragment;
import com.yoomiito.app.ui.fragment.GoodsSortListFragment;
import com.yoomiito.app.ui.search.SearchResultActivity;
import com.yoomiito.app.service.AppService;
import com.yoomiito.app.ui.fragment.FindFragment;
import com.yoomiito.app.ui.fragment.HomeFragment;
import com.yoomiito.app.ui.fragment.my.MyFragment;
import com.yoomiito.app.ui.songduoduo.SendMoreFragment;
import com.yoomiito.app.utils.AllCode;
import com.yoomiito.app.utils.AllUtils;
import com.yoomiito.app.utils.BottomNavigationUtil;
import com.yoomiito.app.utils.CacheUtils;
import com.yoomiito.app.utils.DensityUtil;
import com.yoomiito.app.utils.DialogManager;
import com.yoomiito.app.utils.EventMessage;
import com.yoomiito.app.utils.L;
import com.yoomiito.app.utils.LoginUtils;
import com.yoomiito.app.utils.RxBusManager;
import com.yoomiito.app.ui.push.UMManager;
import com.yoomiito.app.utils.Type;
import com.yoomiito.app.utils.UserInfoConfig;
import com.yoomiito.app.utils.wx.WXUtils;
import com.yoomiito.app.widget.dialog.ApkDownloadDialog;
import com.yoomiito.app.widget.dialog.NewVersionDialog;
import com.yoomiito.app.widget.NoScrollViewPager;
import com.yoomiito.app.widget.dialog.PushTipDialog;
import com.yoomiito.app.widget.dialog.SearchDialog;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import cn.droidlover.xdroidmvp.base.XFragmentAdapter;
import cn.droidlover.xdroidmvp.cache.SharedPref;
import cn.droidlover.xdroidmvp.router.Router;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

public class MainActivity extends BaseActivity<MainPresenter> {

    @BindView(R.id.vp)
    NoScrollViewPager vp;
    @BindView(R.id.bottomNavigationView)
    BottomNavigationView bottomNavigationView;

    private NewVersionDialog newVersionDialog;
    private File mApkFile;
    private ApkDownloadDialog apkDownloadDialog;
    private VersionInfo versionInfo;
    private FindFragment mFindFragment;
    private Disposable searchDialogDisposable;

    private int toFm;
    private SearchDialog searchDialog;
    private PushTipDialog pushTipDialog;
    private int homeIconResId = R.mipmap.icon_home_active;
    //    private ImageView iv;//左下底部按钮
//    private LinearLayout ivParentLayout;
    private HomeFragment homeFragment;
    private boolean homeShow = true;

    @Override
    public int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    public MainPresenter newP() {
        return new MainPresenter(App.mAppConfig);
    }

    /**
     * 仅用于 推送商品跳转
     *
     * @param context
     * @param tab
     */
    public static void start(Context context, int tab) {
        Intent intent = new Intent(context, MainActivity.class);
        intent.putExtra(Constant.ToFM, tab);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        String token = SharedPref.getInstance(this).getString(Constant.TOKEN, "");
        if (!TextUtils.isEmpty(token)) {
            super.initData(savedInstanceState);
        }
        if (savedInstanceState != null) {
            App.mAppConfig.mCurrentUser.mUserInfo = (UserInfo) savedInstanceState.getSerializable(Constant.UserInfo);

        }
//        if (App.mAppConfig.getIsLogin()) getP().getLiveInfo();
        getP().getConfig();
        RxBusManager.subscribeRxBusManager(this, Constant.DATA, new RxBus.Callback<VersionInfo>() {
            @Override
            public void onEvent(VersionInfo info) {
                if (info.getFile() == null) {
                    newVersionDialog.dismiss();
                    showLoadDialog();
                    apkDownloadDialog.setProgress(info.getProgress());
                } else {
                    apkDownloadDialog.setClick(true);
                    if (0 == versionInfo.getIs_force()) {//普通更新
                        apkDownloadDialog.dismiss();
                        DialogManager.Companion.getMInstance().setStopShow(false);
                        DialogManager.Companion.getMInstance().show();
                    }
                    mApkFile = info.getFile();
                    install(mApkFile);
                }
            }
        });

        initViewPager();
        initBottomView();
        Intent intent = getIntent();
        if (intent != null) {
            String pushMsg = intent.getStringExtra(Constant.UM_PUSH_MESSAGE);
            if (!TextUtils.isEmpty(pushMsg)) {
//                BannerAndIconInfo bannerInfo = JSONObject.parseObject(pushMsg, BannerAndIconInfo.class);
//               handleActFromType(bannerInfo);
                //放到HomeRecommendFragment处理
                EventMessage eventMessage = new EventMessage();
                eventMessage.setEventType(Type.EventMsgType.CustomAdMeg);
                eventMessage.setMsg(pushMsg);
                EventBus.getDefault().postSticky(eventMessage);
                L.i("透传消息已发");

            }
        }
        if (versionInfo != null) {
            setVersionInfo(versionInfo);
        } else {
            getP().getNewVersion();
        }
//        String[] s = getTestDeviceInfo(this);
//        for (String s0:s) {
//            Log.i("YOM","S:"+s0);
//        }
    }
//
//    public static String[] getTestDeviceInfo(Context context){
//        String[] deviceInfo = new String[2];
//        try {
//            if(context != null){
//                deviceInfo[0] = DeviceConfig.getDeviceIdForGeneral(context);
//                deviceInfo[1] = DeviceConfig.getMac(context);
//            }
//        } catch (Exception e){
//        }
//        return deviceInfo;
//    }

    public void showPushDialog() {
        if (NotificationManagerCompat.from(context).areNotificationsEnabled()) {
            if (pushTipDialog != null) pushTipDialog.dismiss();
        } else if (!CacheUtils.INSTANCE.isFirstShowPushTipDialog()) {
            if (pushTipDialog == null) pushTipDialog = new PushTipDialog(this);
            pushTipDialog.show();
            DialogManager.Companion.getMInstance().addManager(DialogManager.Companion.getMInstance().getPUSHDIALOG(), pushTipDialog);
        }
    }

    private void initBottomView() {
//        BottomNavigationMenuView menuView = (BottomNavigationMenuView) bottomNavigationView.getChildAt(0);
//        BottomNavigationItemView itemView = (BottomNavigationItemView) menuView.getChildAt(0);
//        ivParentLayout = new LinearLayout(this);
//        ivParentLayout.setGravity(Gravity.CENTER);
//        ivParentLayout.setBackgroundResource(R.color.color_white);
//        iv = new ImageView(context);
//        iv.setId(R.id.bottom_item_view);
//        iv.setImageResource(R.mipmap.icon_home_active);
//        FrameLayout.LayoutParams ivlp = new FrameLayout.LayoutParams(DensityUtil.dp2px(38), DensityUtil.dp2px(38));
//        ivlp.gravity = Gravity.CENTER;
//        ivParentLayout.addView(iv, ivlp);
//        FrameLayout.LayoutParams parentLp = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
//        itemView.addView(ivParentLayout, parentLp);

        bottomNavigationView.setItemIconTintList(null);
        bottomNavigationView.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
        BottomNavigationUtil.disableShiftMode(bottomNavigationView, context);
        bottomNavigationView.setSelectedItemId(R.id.navigation_home);
    }

    private void initViewPager() {
        homeFragment = new HomeFragment();
//        mFindFragment = new FindFragment();

        List<Fragment> list = new ArrayList<>();
        list.add(homeFragment);
//        list.add(new GiftActivity());
        list.add(new GiftFragment());
        list.add(new GoodsSortListFragment());
        list.add(new FindFragment());
        list.add(new MyFragment());
        XFragmentAdapter fragmentAdapter = new XFragmentAdapter(getSupportFragmentManager(), list, null);
        vp.setAdapter(fragmentAdapter);
        vp.setOffscreenPageLimit(4);
        vp.setScroll(false);
    }

//    private Handler mHandler = new Handler();

    @Override
    protected void onStart() {
        super.onStart();
        if (UserInfoConfig.getUserId() != 0) {
            UMManager.INSTANCE.addAlias(String.valueOf(UserInfoConfig.getUserId()));
        }
//        showPushDialog();
        if (App.mAppConfig.getIsLogin()) getP().getUserInfo();
//        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.P) {
//            /*
//                Android 10 除非您的应用是默认输入法 (IME) 或是目前处于焦点的应用，否则它无法访问 Android 10 或更高版本平台上的剪贴板数据。
//                解决方案：1、等activity绘制完成界面再获取剪贴板：
//                            this.getWindow().getDecorView().post(new Runnable() {
//                                @Override
//                                public void run() {
//                                    //获取到剪贴板内容
//                                }
//                            });
//                         2、延迟一段时间（如500ms或1000ms等）再获取剪贴板。目前使用该方案。
//             */
//            searchDialogDisposable = Observable.timer(500, TimeUnit.MILLISECONDS)
//                    .compose(bindToLifecycle())
//                    .subscribeOn(Schedulers.io())
//                    .observeOn(AndroidSchedulers.mainThread())
//                    .subscribe(aLong -> {
//                        readClipbordContent();
//                        searchDialogDisposable.dispose();
//                        searchDialogDisposable = null;
//                    });
//        } else {
//            readClipbordContent();
//        }

    }

    private void readClipbordContent() {
        String content = AllUtils.getClipbordContent();
        List<String> searchList = SharedPref.getInstance(App.getInstance()).getListData(Constant.HISTORY, String.class);
        String historyContent = SharedPref.getInstance(App.getApplication()).getString(Constant.SEARCH_KEY, "");
//        L.i("剪贴板："+content+"  "+!TextUtils.isEmpty(content) +"  "+ !historyContent.equals(content) +"   "+ !serachList.contains(content));
        if (!TextUtils.isEmpty(content) && !historyContent.equals(content) && !searchList.contains(content)) {//不能为空  跟上次不同  搜索记录没有
            showSearchDialog(content);
            SharedPref.getInstance(App.getApplication()).putString(Constant.SEARCH_KEY, content);
        }

    }

    @Override
    protected void onNewIntent(Intent intent) {
//        super.onNewIntent(intent);
        toFm = intent.getIntExtra(Constant.ToFM, -1);
        if (toFm != -1) {
            switchFm(toFm);
        }
    }

    private int[] itemResIds = {R.id.navigation_home, R.id.navigation_dashboard, R.id.youmi_oilcard, R.id.navigation_notifications, R.id.navigation_person};
    private int[] itemUnIcon = {R.mipmap.home, R.mipmap.gift, R.drawable.icon_video, R.mipmap.find, R.mipmap.my};
    private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener = new BottomNavigationView.OnNavigationItemSelectedListener() {

        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem item) {
            int i = -1;
            switch (item.getItemId()) {
                case R.id.navigation_home:
//                    item.setIcon(R.mipmap.home_active);
                    item.setIcon(homeIconResId);
                    item.setTitle(R.mipmap.icon_home_back==homeIconResId?"回顶部":"首页");
                    if (homeShow && homeIconResId == R.mipmap.icon_home_back) {
                        EventMessage eventMessage = new EventMessage();
                        eventMessage.setEventType(Type.EventMsgType.HomeScrollTop);
                        EventBus.getDefault().post(eventMessage);
                    }
                    homeShow = true;
                    i = 0;
                    break;
                case R.id.navigation_dashboard:
                    item.setIcon(R.mipmap.gift_active);
                    i = 1;
                    break;

                case R.id.youmi_oilcard:
                    i = 2;
//                    if (App.mAppConfig.getIsLogin()) {
//
//
//                    } else {
//                        if (AllUtils.isFastClick()) {
//                            return true;
//                        }
////                        AllUtils.toLogin(MainActivity.this, AllCode.LoginIn);
//                        LoginUtils.INSTANCE.toOneKeyLogin(MainActivity.this);
//                        return false;
//                    }
                    break;

                case R.id.navigation_notifications:
//                    if (UserInfoConfig.getCompanyId() == 1) {
                    item.setIcon(R.mipmap.find_active);
//                    } else {
//                        item.setIcon(R.drawable.tabbar_gmh_selected);
//                    }
                    i = 3;
//                    WXUtils.INSTANCE.openMiniProgram(MainActivity.this, "/pages/lives/index");
                    break;

                case R.id.navigation_person:
                    if (App.mAppConfig.getIsLogin()) {
                        item.setIcon(R.mipmap.my_active);
                        i = 4;
                    } else {
                        if (AllUtils.isFastClick()) {
                            return true;
                        }
//                        AllUtils.toLogin(MainActivity.this, AllCode.LoginIn);
                        LoginUtils.INSTANCE.toOneKeyLogin(MainActivity.this);
                        return false;
                    }
                    break;
            }
//            ivParentLayout.setVisibility(i == 0 ? View.VISIBLE : View.GONE);
            vp.setCurrentItem(i);
//            vp.setCurrentItem(i == 3 ? vp.getCurrentItem() : (i > 3 ? (i - 1) : i));
            setUnSelectIcon(i);
            return true;
        }
    };

    public void changeYouMiIv(boolean show) {
        homeIconResId = show ? R.mipmap.icon_home_back : R.mipmap.icon_home_active;
        if (homeShow) {
            MenuItem menuItem = bottomNavigationView.getMenu().findItem(itemResIds[0]);
            menuItem.setIcon(homeIconResId);
            menuItem.setTitle(show?"回顶部":"首页");
        }
//        iv.setImageResource(homeIconResId);
    }

    @Override
    public void eventMessage(EventMessage eventMessage) {
        if (AllCode.LoginOut.equals(eventMessage.getEventType())
//                ||AllCode.LoginSuccess.equals(eventMessage.getEventType())) {
        ) {

            switchFm(0);
//            bottomNavigationView.getMenu().findItem(R.id.navigation_notifications).setTitle("优米圈");
//            bottomNavigationView.getMenu().findItem(R.id.navigation_notifications).setIcon(R.mipmap.find);
//            itemUnIcon[2] = R.mipmap.find;
        }
        if (AllCode.LoginSuccess.equals(eventMessage.getEventType())) {//选中的图标会根据公司来动态切换
//
//            boolean flag = UserInfoConfig.getCompanyId() == 1;
//            L.i("登录成功： 公司：" + flag);
//            bottomNavigationView.getMenu().findItem(R.id.navigation_notifications).setTitle(flag ? "优米圈" : "瑰秘圈");
//            if (vp.getCurrentItem() == 2) {
//                bottomNavigationView.getMenu().findItem(R.id.navigation_notifications).setIcon(flag ? R.mipmap.find_active : R.drawable.tabbar_gmh_selected);
//            } else {
//                itemUnIcon[2] = flag ? R.mipmap.find : R.drawable.guimi;//不会根据公司来动态切换  所以需要更换数组数据  待优化
//                bottomNavigationView.getMenu().findItem(R.id.navigation_notifications).setIcon(itemUnIcon[2]);
//            }
        }
    }

    private void setUnSelectIcon(int position) {
        for (int i = 0; i < itemResIds.length; i++) {
            if (i != position && i != 2) {
                MenuItem menuItem = bottomNavigationView.getMenu().findItem(itemResIds[i]);
                if (i == 0) {
                    homeShow = false;
                    menuItem.setTitle("首页");
                }
                menuItem.setIcon(itemUnIcon[i]);
            }
        }
    }

    public void switchFm(int p) {
        vp.setCurrentItem(p);
        bottomNavigationView.setSelectedItemId(getBottomId(p));
    }

    private int getBottomId(int p) {
        switch (p) {
            case 0:
                return R.id.navigation_home;
            case 1:
                return R.id.navigation_dashboard;
            case 2:
                return R.id.youmi_oilcard;
            case 3:
                return R.id.navigation_notifications;
            case 4:
                return R.id.navigation_person;
        }
        return -1;
    }

    public void setLiveUserInfo(LiveUserInfo liveUserInfo) {
        if (liveUserInfo != null) {
            App.mLiveInfo = liveUserInfo;
        }
    }

    public void setVersionInfo(VersionInfo versionInfo) {
        this.versionInfo = versionInfo;
        if (versionInfo == null) {
            DialogManager.Companion.getMInstance().addManager(DialogManager.Companion.getMInstance().getUPDATE_APK(), null);
            return;
        }
        int currentCode = AllUtils.getVersionInfo().versionCode;
//        currentCode = 392;
        Log.e("xing","http currentCode = " + currentCode  + "   versionInfo.getApp_code() = " + versionInfo.getApp_code());
        if (versionInfo.getApp_code() > currentCode) {
            showNewVersion();
        } else {
            DialogManager.Companion.getMInstance().addManager(DialogManager.Companion.getMInstance().getUPDATE_APK(), null);
        }
    }

    public void showSearchDialog(String ss) {
        if (searchDialog == null) {
            searchDialog = new SearchDialog(this);
            searchDialog.setOnViewClickListener(view -> {
                toSearch(searchDialog.getContent());
                searchDialog.dismiss();
            });
        }

        if (newVersionDialog == null || !newVersionDialog.isShowing()) {
//            searchDialog.setContent(ss).show();
            searchDialog.setContent(ss);
            DialogManager.Companion.getMInstance().addManager(DialogManager.Companion.getMInstance().getSEARCHDIALOG(), searchDialog);
        }

    }

    private void toSearch(String content) {
        CacheUtils.INSTANCE.saveTaoBaoSearchHistory(content);
        Router.newIntent(MainActivity.this)
                .to(SearchResultActivity.class)
                .putString(Constant.KEY, content)
                .launch();
    }

    //加载dialog
    public void showLoadDialog() {
        if (apkDownloadDialog == null) {
            apkDownloadDialog = new ApkDownloadDialog(this);
            apkDownloadDialog.setSize(versionInfo.getApp_size());
            apkDownloadDialog.setOnClickListener(() -> {
                install(mApkFile);
            });
        }
        apkDownloadDialog.show();
    }

    //版本更新dialog  下个版本增加权限判断
    private void showNewVersion() {
        if (newVersionDialog == null) {
            newVersionDialog = new NewVersionDialog(this)
                    .setOnClickListener(isSure -> {
                        newVersionDialog.dismiss();
                        DialogManager.Companion.getMInstance().setStopShow(true);
                        startDownload();
                    });
        }
        if (searchDialog == null || !searchDialog.isShowing()) {
            int currentCode = AllUtils.getVersionInfo().versionCode;
            //(versionInfo.getForce_app_code() > currentCode)
            newVersionDialog.setMustUpdate((1 == versionInfo.getIs_force()) ? true : false);
            newVersionDialog.setSize(versionInfo.getApp_size())
                    .setVersionName("V" + versionInfo.getApp_version())
                    .setContent(versionInfo.getContent().replace("|", "\n"));
            newVersionDialog.show();
//            DialogManager.Companion.getMInstance().addManager(DialogManager.Companion.getMInstance().getUPDATE_APK(), newVersionDialog);
        }
    }

    private void startDownload() {
        AllUtils.requestPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .subscribe(aBoolean -> {
                    if (aBoolean) {
                        Intent intent = new Intent(MainActivity.this, AppService.class);
                        intent.putExtra(Constant.TYPE, AllCode.AppDownload);
                        intent.putExtra(Constant.DATA, versionInfo.getDownload_url());
//                        intent.putExtra(Constant.DATA, "https://mimitao-cdn.aijiamai.com/apks/v1.1.6.2.apk");
                        startService(intent);
                        Log.e("xing","http currentCode = " + versionInfo.getDownload_url() );

                    }
                });
    }

    private int INSTALL_PERMISSION_CODE = 99;

    private void install(File file) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            if (AllUtils.haveInstallApk()) {
                installApp(file);
            } else {
                Uri packageUri = Uri.parse("package:" + App.getInstance().getPackageName());
                Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, packageUri);
                startActivityForResult(intent, INSTALL_PERMISSION_CODE);
            }
        } else {
            installApp(file);
        }
    }

    private void installApp(File file) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            Uri contentUri = FileProvider.getUriForFile(App.getInstance(), "com.qiannianai.app.fileProvider", file);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
        } else {
            intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
        }
        startActivity(intent);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == INSTALL_PERMISSION_CODE && resultCode == RESULT_OK) {
            installApp(mApkFile);
        }

//        else if (resultCode == CiclePublishActivity.CODE_PUBLISH_CICLE){
//            if (mFindFragment != null){
//                mFindFragment.onActivityResult(requestCode,resultCode,data);
//            }
//        }
    }

//    /**
//     * 防止fragment重叠
//     *
//     * @param outState
//     */
//    @Override
//    public void onSaveInstanceState(Bundle outState) {
////        super.onSaveInstanceState(outState);
//        outState.putSerializable(Constant.UserInfo, App.mAppConfig.mCurrentUser.mUserInfo);
//    }


    @Override
    public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
        outState.putSerializable(Constant.UserInfo, App.mAppConfig.mCurrentUser.mUserInfo);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        App.mAppConfig.mCurrentUser.mUserInfo = (UserInfo) savedInstanceState.getSerializable(Constant.UserInfo);
    }

    @Override
    protected void onDestroy() {
        RxBusManager.unregisterRxBusManager(this);
        super.onDestroy();

    }
}